package net.sppan.blog.controller.admin;

import net.sppan.blog.common.JsonResult;
import net.sppan.blog.config.SiteConfig;
import net.sppan.blog.controller.BaseController;
import net.sppan.blog.entity.Options;
import net.sppan.blog.exception.ServiceException;
import net.sppan.blog.service.OptionsService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

@Controller
@RequestMapping("/admin/system")
public class AdminOptionsController extends BaseController {

    @Resource
    private OptionsService optionsService;

    @Resource
    private SiteConfig siteConfig;

    @Resource
    private ServletContext servletContext;

    @GetMapping("/index")
    public String index() {
        return "admin/system/index";
    }
    @GetMapping("{id}/upload")
    public String upload(@PathVariable("id") Long id,ModelMap map) {
        map.put("id", id);
        return "admin/system/upload";
    }
    @PostMapping("/list")
    @ResponseBody
    public Page<Options> list() {
        PageRequest pageRequest = getPageRequest();
        Page<Options> page = optionsService.findAll(pageRequest);
        return page;
    }

    @GetMapping("/form")
    public String form(@RequestParam(required=false) Long id,
                       ModelMap map
    ){
        if(id != null){
            Options options = optionsService.findById(id);
            map.put("options", options);
        }
        return "admin/system/form";
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResult save(Options options){
        try {
            optionsService.saveOrUpdate(options);
        }catch (ServiceException e) {
            e.printStackTrace();
            return JsonResult.fail(e.getMessage());
        }
        siteConfig.setOptions();
        return JsonResult.ok();
    }


    @PostMapping("/upload/{id}")
    @ResponseBody
    public JsonResult upload(@RequestParam("file") MultipartFile file,@PathVariable("id") Long id){
        Options options = optionsService.findByOptionKey(optionsService.findById(id).getOptionKey());
        System.err.println(id);
        System.err.println(file.getOriginalFilename());
        String relativePath;
        String newFileName;
        try {
            if(!isLogin()){
                return JsonResult.create("success", false).set("msg", "没有登录不能上传文件");
            }
            if (null == file) {
                return JsonResult.create("success",false).set("msg", "上传文件为 null");
            }
            // 获取上传的文件名
            String fileName = file.getOriginalFilename();
            // 获取文件的后缀名
            String extName = fileName .substring(fileName.lastIndexOf("."));
            // 文件保存的相对位置，相对于upload
            relativePath = File.separator + "i" + File.separator;
            // 生成的文件名
            newFileName = generateFileName(id, extName);
            // 文件保存的完整目录
            String absolutePath = servletContext.getRealPath("static\\front") + relativePath;
            System.err.println(absolutePath);
            File temp = new File(absolutePath);
            if (!temp.exists()) {
                temp.mkdirs();  // 如果目录不存在则创建
            }
            BufferedOutputStream stream = null;
            stream = new BufferedOutputStream(new FileOutputStream(absolutePath + newFileName));
            if(stream != null){
                stream.write(file.getBytes());
                stream.close();
            }
            //返回给编辑器的文件位置
            String resultFilePath = File.separator + "static\\front" + relativePath + newFileName;
            System.err.println(resultFilePath);
            options.setOptionValue(resultFilePath);
            optionsService.saveOrUpdate(options);
            siteConfig.setOptions();
            String path = servletContext.getRealPath("\\");
            System.err.println(path);
            return JsonResult.create("success", true).set("msg", "上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.create("success",false).set("msg", e.getMessage());
        }
    }

    /**
     * 生成规范的文件名
     */
    private String generateFileName(Long id, String extName) {
        return id + "_" + System.currentTimeMillis() + extName;
    }
}
